import hmac
import hashlib
import requests
import sys
import time
import base64
import json
from collections import OrderedDict

class Fcoin():
    #初始化，获取地址
    def __init__(self,base_url = 'https://api.fcoin.com/v2/'):
        self.base_url = base_url

    def auth(self, key, secret):
        #使用bytes类，将传入的字符串key  secret 按照utf8进行编码
        self.key = bytes(key,'utf-8') 
        self.secret = bytes(secret, 'utf-8') 

    #方法method，地址api_url，传入关键字参数payload
    def public_request(self, method, api_url, **payload):
        """request public url"""
        # base_url
        r_url = self.base_url + api_url
        try:
            r = requests.request(method, r_url, params=payload)
            #JSON 会被解码返回。要检查请求是否成功，请使用
            # r.raise_for_status() 或者检查 r.status_code 是否和你的期望相同
            r.raise_for_status()
        except requests.exceptions.HTTPError as err:
            print(err)
        if r.status_code == 200:
            return r.json()

    #base64,hmac
    def get_signed(self, sig_str):
        """signed params use sha512"""
        # 使用base64进行简单的加密
        sig_str = base64.b64encode(sig_str)
        # hmac用法，hmac.new(key[, msg[, digestmod]])
        signature = base64.b64encode(hmac.new(self.secret, sig_str, digestmod=hashlib.sha1).digest())
        return signature


    def signed_request(self, method, api_url, **payload):
        """request a signed url"""
        param=''
        if payload:
            sort_pay = sorted(payload.items())
            #sort_pay.sort()
            for k in sort_pay:
                param += '&' + str(k[0]) + '=' + str(k[1])
            #去除最左边的&符号
            param = param.lstrip('&')
        #时间戳
        timestamp = str(int(time.time() * 1000))
        full_url = self.base_url + api_url

        if method == 'GET':
            #若参数存在
            if param:
                full_url = full_url + '?' +param
            sig_str = method + full_url + timestamp
        elif method == 'POST':
            sig_str = method + full_url + timestamp + param

        signature = self.get_signed(bytes(sig_str, 'utf-8'))

        headers = {
            'FC-ACCESS-KEY': self.key,
            'FC-ACCESS-SIGNATURE': signature,
            'FC-ACCESS-TIMESTAMP': timestamp

        }

        try:
            r = requests.request(method, full_url, headers = headers, json=payload)
            r.raise_for_status()
        except requests.exceptions.HTTPError as err:
            print(err)
            print(r.text)
        if r.status_code == 200:
            return r.json()


    def get_server_time(self):
        """Get server time"""
        return self.public_request('GET','/public/server-time')['data']

    # 获取货币
    def get_currencies(self):
        """get all currencies"""
        return self.public_request('GET', '/public/currencies')['data']

    def get_symbols(self):
        """get all symbols"""
        return self.public_request('GET', '/public/symbols')['data']

    def get_market_ticker(self, symbol):
        """get market ticker"""
        return self.public_request('GET', 'market/ticker/{symbol}'.format(symbol=symbol))

    # 获取市场交易深度
    def get_market_depth(self, level, symbol):
        """get market depth"""
        return self.public_request('GET', 'market/depth/{level}/{symbol}'.format(level=level, symbol=symbol))

    # 获取交易
    def get_trades(self,symbol):
        """get detail trade"""
        return self.public_request('GET', 'market/trades/{symbol}'.format(symbol=symbol))

    # 获取差额
    def get_balance(self):
        """get user balance"""
        return self.signed_request('GET', 'accounts/balance')

    # 获取订单列表
    def list_orders(self, **payload):
        """get orders"""
        return self.signed_request('GET','orders', **payload)

    # 创建订单
    def create_order(self, **payload):
        """create order"""
        return self.signed_request('POST','orders', **payload)

    # 下单购买
    def buy(self,symbol, price, amount):
        """buy someting"""
        return self.create_order(symbol=symbol, side='buy', type='limit', price=str(price), amount=amount)

    # 下单卖
    def sell(self, symbol, price, amount):
        """buy someting"""
        return self.create_order(symbol=symbol, side='sell', type='limit', price=str(price), amount=amount)
    # 获取某单个订单
    def get_order(self,order_id):
        """get specfic order"""
        return self.signed_request('GET', 'orders/{order_id}'.format(order_id=order_id))

    # 取消订单
    def cancel_order(self,order_id):
        """cancel specfic order"""
        return self.signed_request('POST', 'orders/{order_id}/submit-cancel'.format(order_id=order_id))

    # 检查订单结果
    def order_result(self, order_id):
        """check order result"""
        return self.signed_request('GET', 'orders/{order_id}/match-results'.format(order_id=order_id))
    # 获取数据
    def get_candle(self,resolution, symbol, **payload):
        """get candle data"""
        return self.public_request('GET', 'market/candles/{resolution}/{symbol}'.format(resolution=resolution, symbol=symbol), **payload)


